<?php

namespace App\Libs\Session;
use \Phalcon\DI;
use \App\Libs\Cache\Redis;
class AppSession extends \App\Libs\Base\AccessObject
{
    static $table = 't_anxin_session';


    public function getUser() {
        return $this->getObject();
    }

    private static function generate($uid) {
        return  md5(md5($uid . ':' . mt_rand(1, 1000)) . microtime());
    }

    /**
     * for  login
     */
    public static function save($user) {
        $key = self::generate($user['id']);

        unset($user['password']);
        // session
        \App\Libs\Cache\Redis::set($key, 3600*24*30 ,$user);

        // cookies
        //$i = setcookie(SESSION_KEY, $key, time() + 7200, '/', DOMAIN);
        // save DB
        \App\Libs\DB\AnxinPdo::insert(self::$table, array(
            'uid' => $user['id'],
            'key' => $key,
            'ctime' => date('Y-m-d H:i:s'),
            'itime' => date('Y-m-d H:i:s', time() + 3600)
        ));

        return  $key;
    }

    /**
     * for user update
     */
    public static function resetCache($user) {
        $key = trim($_COOKIE[SESSION_KEY]);
        \App\Libs\Cache\Memcached::set(self::$prefix . $key, $user, 3600);
    }

    /**
     * for check login
     */
    public static function load($key) {
       // if (isset($_COOKIE[SESSION_KEY]) && ! empty($_COOKIE[SESSION_KEY])) {

           // $key = trim($_COOKIE[SESSION_KEY]);
            $user = \App\Libs\Cache\Redis::get($key);
            // session expire or cache failure
            if (empty($user)) {
                $sql = 'SELECT uid FROM ' . self::$table . ' WHERE `key`=:key ';
                $uid = \App\Libs\DB\AnxinPdo::scalar($sql, array(
                    'key' => $key
                    
                ));
                if (empty($uid)) {
                    return NULL;
                }
                 $getUserInfoSql = "SELECT id,username,tel,head_url,credential_type,credential_no,email,unionid,score FROM t_anxin_user_info  WHERE id = ?";
                $user = AnxinPdo::find( $getUserInfoSql,  array($uid) );
                Redis::setex($key,3600*24*30,json_encode($user));
             
            }
            $user = json_decode($user,true);
            return $user;
        //}
       // return NULL;
    }

    /**
     * for logout
     */
    public static function destroy() {
        if (isset($_COOKIE[SESSION_KEY]) && ! empty($_COOKIE[SESSION_KEY])) {
            $key = trim($_COOKIE[SESSION_KEY]);
            \App\Libs\Cache\Memcached::delete(self::$prefix . $key);
        }
        setcookie(SESSION_KEY, '', 0, '/', DOMAIN);
    }
}
